import * as axios from 'axios';

export default class ReqRateLimiter {
  constructor() {
    this.reqRecorder = {};
    // 单位：ms
    this.throttlingTime = 500;
    this.throttlingMethods = ['post', 'put', 'patch', 'delete'];
  }

  generateKey({ url, method }) {
    return `${method}:${url}`;
  }

  add(reqConfig) {
    if (this.throttlingMethods.includes(reqConfig.method)) {
      const key = this.generateKey(reqConfig);
      if (this.reqRecorder[key] && Date.now() - (this.reqRecorder[key] < this.throttlingTime)) {
        let cancel;
        reqConfig.cancelToken = new axios.CancelToken(function executor(c) {
          // executor 函数接收一个 cancel 函数作为参数
          cancel = c;
        });
        cancel('request too frequently');
      } else {
        this.reqRecorder[key] = Date.now();
      }
    }
  }

  cancel(reqConfig) {
    if (this.throttlingMethods.includes(reqConfig.method)) {
      const key = this.generateKey(reqConfig);
      delete this.reqRecorder[key];
    }
  }
}
